import { BrowserWindow, BrowserView, ipcMain, globalShortcut } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import updateHandle from './../lib/electron-update'
let win

const createWindow = async function () {
  // Create the browser window.
  win = new BrowserWindow({
    width: 960,
    height: 600,
    center: true,
    show: true,
    resizable: false,
    titleBarStyle: 'customButtonsOnHover',
    frame: false,
    transparent: true,
    hasShadow: true,
    webPreferences: {
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      webSecurity: false,
      contextIsolation: false,
      enableRemoteModule: true
    }
  })

  win.on('closed', () => {
    win = null
  })

  // 快捷键的注册-打开调试框
  globalShortcut.register('CTRL+SHIFT+I', () => {
    if (win) win.webContents.openDevTools()
  })

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(`${process.env.WEBPACK_DEV_SERVER_URL}/login.html`)
    // 本地测试，打开调试框
    if (!process.env.IS_TEST) win.webContents.openDevTools()
  } else {
    createProtocol('app')
    // Load the index.html when not in development
    win.loadURL('app://./login.html')
  }
}

const getWindow = function () {
  return win
}

// 升级窗口
ipcMain.on('update-view', function (event, msg) {
  // 创建升级窗口
  const view = new BrowserWindow({
    show: true,
    width: 600,
    height: 380,
    resizable: false,
    titleBarStyle: 'customButtonsOnHover',
    frame: false,
    hasShadow: true,
    webPreferences: {
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      webSecurity: false,
      contextIsolation: false,
      enableRemoteModule: true
    }
  })

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    view.loadURL(`${process.env.WEBPACK_DEV_SERVER_URL}/update/index.html`)
  } else {
    createProtocol('app')
    // Load the index.html when not in development
    view.loadURL('app://./update/index.html')
  }

  ipcMain.on('close-update-window', () => {
    view.hide()
  })

  ipcMain.on('register-update', (e, urlString) => {
    updateHandle(view, urlString, (text, obj) => {
      view.webContents.send('update-result', { text, obj })
    })
  })
})

// 关闭窗口
ipcMain.on('login-win-close', function (event, msg) {
  win.close()
})

// 关闭窗口
ipcMain.on('window-close', function (event, msg) {
  setTimeout(() => {
    win.webContents.send('setPrinter', ['list'])
  }, 3000)
})

// win.webContents.send('chat-show', '')

export default {
  createWindow,
  getWindow
}
